package stewardapplet

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogap/logs"
	"go.uber.org/zap"
	"log"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/couponinfo"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/orders"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
	"yundian/internel/pkg/wxpay"
)

// ------------微信支付相关请求处理---------------//

var payClient = wxpay.NewPayClient(nil)

// HandleLogin 微信小程序登录
func HandleLogin(ctx *gin.Context) {
	param := &struct {
		Code string `form:"code" binding:"required"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	wc := logic.NewSettingLogic().GetPaySetting()

	respData, err := payClient.Login(param.Code, wc.AppId, wc.AppSecret)
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}
	logs.Info("打印测试--------登录信息返回", respData, wc.AppId, wc.AppSecret)
	// 处理业务逻辑
	loginResult, err := logic.NewWxAuthLogic().HandleLogicLogin(respData, wc.AppId)
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}

	// 响应给前端
	loginResult.Host = global.Cfg.Ali.AliossPath
	Response(ctx)("", CodeSuccess, loginResult)(OK)
}

// HandleLogin 微信小程序登录
func HandleLoginWifi(ctx *gin.Context) {
	param := &struct {
		Code string `form:"code" binding:"required"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	wc := logic.NewSettingLogic().GetPaySetting()

	respData, err := payClient.Login(param.Code, wc.AppId, wc.AppSecret)
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}

	// 处理业务逻辑
	loginResult, err := logic.NewWxAuthLogic().HandleLogicLoginWifi(respData, wc.AppId)
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}

	// 响应给前端
	loginResult.Host = global.Cfg.Ali.AliossPath
	Response(ctx)("", CodeSuccess, loginResult)(OK)
}

// HandleMemberInfo 更新用户信息
func HandleMemberInfo(ctx *gin.Context) {
	param := &request.MemberInfoReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	log.Println("打印测试数据-更新用户信息", param)

	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	openid, err := helper.GetUserNameFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 获取sessionKey
	rdbSessionKey := utils.Join(openid, "-sessionKey")
	sessionKey := global.Rdb.Get(ctx, rdbSessionKey).Val()
	sign := wechatpay.SHA1(param.RawData, sessionKey)

	log.Println("sessionKey-sign", rdbSessionKey, sessionKey, sign)
	if sign != param.Signature {
		Response(ctx)("签名不一致", CodeError, nil)(Error)
		return
	}

	wc := logic.NewSettingLogic().GetPaySetting()

	// 解密微信数据
	pc := wechatpay.NewWXUserDataCrypt(wc.AppId, sessionKey)
	userInfo, err := pc.Decrypt(param.EncryptedData, param.Iv)
	if err != nil {
		Response(ctx)("解密失败", CodeError, err.Error())(Error)
		return
	}
	log.Println("解密后的用户信息", userInfo)

	// 更新用户信息逻辑
	logic.NewWxAuthLogic().UpdateMemberInfo(userInfo, userId)

	Response(ctx)("获取会员授权信息成功", CodeSuccess, userInfo)(OK)
}

func HandleGetUserInfoByOpenId(ctx *gin.Context)  {
	param := &struct {
		Openid    string `form:"openid" json:"openid"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	if param.Openid == "" {
		Response(ctx)("参数错误", CodeError, false)(Error)
		return
	}
	data := memberdao.NewMemberDao().GetUserInfoByOpenid(param.Openid)
	if data.Err != nil {
		Response(ctx)("读取失败", CodeError, false)(Error)
		return
	}
	Response(ctx)("读取成功", CodeSuccess, data.Unwrap())(OK)
}

// 获取会员信息
func HandleGetMemberInfoByOpenidAndAppid(ctx *gin.Context)  {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &struct {
		Openid    string `form:"openid" json:"openid"`
		Appid     string `form:"appId" json:"appId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	//data := memberdao.NewMemberDao().GetMemberInfoByOpenidAndAppId(param.Openid, param.Appid)
	data := memberdao.NewMemberDao().GetMemberInfoById(userId)
	Response(ctx)("会员信息获取成功", CodeSuccess, data.Unwrap())(OK)
}

// 会员提现
func HandleSumbitCashSubmit(ctx *gin.Context)  {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &struct {
		Openid    string `form:"openid" json:"openid"`
		Appid     string `form:"appId" json:"appId"`
		Amount     int64 `form:"amount" json:"amount"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	if param.Openid == "" || param.Appid == "" {
		Response(ctx)("获取失败,openid与appid不能为空", CodeError, false)(Error)
		return
	}
	if param.Amount <= 0 {
		Response(ctx)("提现金额不能为空", CodeError, false)(Error)
		return
	}
	// 获取订单
	sql := "select * from orders where openid = ? and state = 5 order by id desc"
	var lists []*orders.OrderModel
	global.Orm.Raw(sql, param.Openid).Find(&lists)
	t := time.Now()

	amount := param.Amount
	// 从订单中原路返回，这样客诉好处理
	for _, lst := range lists {
		stamp := time.Unix(int64(lst.CreateAt), 0)
		memberInfo := memberdao.NewMemberDao().GetMemberInfoByOpenidAndAppId(param.Openid, param.Appid).Unwrap().(*membermodel.MembersModel)
		if memberInfo.Balance <= 0 {
			break
		}
		// 订单小于300天  从订单中原路返回
		if t.Sub(stamp).Hours() <= 7200 {
			balanceInfo := memberdao.NewMemberDao().GetMemberPclBalanceLogInfoByTradeNo(lst.TradeNo, memberInfo.ID).Unwrap().(*membermodel.MemberPclBalance)
			logs.Info("打印测试====>", balanceInfo.Id, balanceInfo.Amount, memberInfo.Balance, amount)
			if balanceInfo.Id > 0 && balanceInfo.Amount > 0 && int64(balanceInfo.Amount) <= memberInfo.Balance && amount > 0 {
				wc := logic.NewSettingLogic().GetPaySettingByAppidAndMchid(lst.Appid, lst.Mchid)
				apiParam := logic.NewOrderLogic().HandleRefundApiParamV3(
					lst,
					lst.OutTradeNo,
					"押金退款",
					int64(balanceInfo.Amount),
					wc.RefundNotifyUrlCash)
				respData, _ := wechatpay.ApiRefundsPayScore(apiParam, wc)

				// 退款进行中或者退款成功
				if (respData.Get("status") == "PROCESSING" && respData.Get("refund_id") != "") || respData.Get("status") == "SUCCESS" {
					// 余额修改
					tx, key := dbs.GormBegin("order refund")
					// 订单退款，退款至余额
					rechargeMoneyUpdateData := memberdao.NewMemberDao().UpdateBalanceAmount(tx, &membermodel.MemberPclBalance{
						MemberId:    memberInfo.ID,
						Amount:      -int(balanceInfo.Amount),
						Type:        4,
						TradeNo:     "R" + lst.TradeNo,
						Description: fmt.Sprintf(`退款提现`),
						CreateTime:  time.Now().Format("2006-01-02 15:04:05"),
						UpdateTime:  time.Now().Format("2006-01-02 15:04:05"),
					})
					if rechargeMoneyUpdateData.Err != nil {
						dbs.GormRollback(tx, key, rechargeMoneyUpdateData.Err)
						continue
					}
					dbs.GormCommit(tx, key)
					amount = amount - int64(balanceInfo.Amount)
				}
			} else {
				continue
			}
		}
		if amount <= 0 {
			break
		}
	}
	// 300天后还有余额的-走转帐
	if amount <= 0 {
		Response(ctx)("提现成功", CodeSuccess, false)(Error)
		return
	}
	memberInfo := memberdao.NewMemberDao().GetMemberInfoByOpenidAndAppId(param.Openid, param.Appid).Unwrap().(*membermodel.MembersModel)
	if memberInfo.Balance != amount {
		Response(ctx)("提现失败", CodeError, false)(Error)
		return
	}
	// 会员ID与当前登录ID不一致
	if userId != memberInfo.ID {
		Response(ctx)("提现失败", CodeError, false)(Error)
		return
	}

	wc := logic.NewSettingLogic().GetPaySettingByAppid(param.Appid)

	// 发起提现
	err = logic.NewOrderLogic().HandleRefundTransfersByXcx(param.Amount, param.Openid, param.Appid, memberInfo, wc, ctx.ClientIP())
	if err != nil {
		Response(ctx)(err.Error(), CodeSuccess, false)(OK)
		return
	}



	//if amount <= 0 {
	//	Response(ctx)("提现失败", CodeError, false)(Error)
	//	return
	//}
	//
	//memberInfo := memberdao.NewMemberDao().GetMemberInfoByOpenidAndAppId(param.Openid, param.Appid).Unwrap().(*membermodel.MembersModel)
	//if memberInfo.Balance != param.Amount {
	//	Response(ctx)("提现失败", CodeError, false)(Error)
	//	return
	//}
	//// 会员ID与当前登录ID不一致
	//if userId != memberInfo.ID {
	//	Response(ctx)("提现失败", CodeError, false)(Error)
	//	return
	//}
	//
	//wc := logic.NewSettingLogic().GetPaySettingByAppid(param.Appid)
	//
	//// 发起提现
	//err = logic.NewOrderLogic().HandleRefundTransfersByXcx(param.Amount, param.Openid, param.Appid, memberInfo, wc, ctx.ClientIP())
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeSuccess, false)(OK)
	//	return
	//}

	Response(ctx)("", CodeSuccess, true)(OK)
}

// 会员提现
func HandleSumbitCashSubmitZfb(ctx *gin.Context)  {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &struct {
		Openid    string `form:"openid" json:"openid"`
		Appid     string `form:"appId" json:"appId"`
		Amount     int64 `form:"amount" json:"amount"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	if param.Openid == "" || param.Appid == "" {
		Response(ctx)("获取失败,openid与appid不能为空", CodeError, false)(Error)
		return
	}
	if param.Amount <= 0 {
		Response(ctx)("提现金额不能为空", CodeError, false)(Error)
		return
	}
	// 获取订单
	sql := "select * from orders where openid = ? and state = 5 order by id desc"
	var lists []*orders.OrderModel
	global.Orm.Raw(sql, param.Openid).Find(&lists)
	t := time.Now()

	amount := param.Amount
	// 从订单中原路返回，这样客诉好处理
	for _, lst := range lists {
		stamp := time.Unix(int64(lst.CreateAt), 0)
		//memberInfo := memberdao.NewMemberDao().GetMemberInfoByOpenidAndAppId(param.Openid, param.Appid).Unwrap().(*membermodel.MembersModel)
		memberInfo := memberdao.NewMemberDao().GetMemberInfoById(userId).Unwrap().(*membermodel.MembersModel)
		if memberInfo.Balance <= 0 {
			continue
		}
		// 订单小于300天  从订单中原路返回
		if t.Sub(stamp).Hours() <= 7200 {
			balanceInfo := memberdao.NewMemberDao().GetMemberPclBalanceLogInfoByTradeNo(lst.TradeNo, memberInfo.ID).Unwrap().(*membermodel.MemberPclBalance)
			balanceInfo1 := memberdao.NewMemberDao().GetMemberPclBalanceLogInfoByRTradeNo(lst.TradeNo, memberInfo.ID).Unwrap().(*membermodel.MemberPclBalance)
			logs.Info("打印测试====>", balanceInfo.Id, balanceInfo.Amount, memberInfo.Balance, amount)
			if balanceInfo.Id > 0 && balanceInfo.Amount > 0 &&
				int64(balanceInfo.Amount) <= memberInfo.Balance &&
				amount > 0 && balanceInfo1.Id <= 0 {

				c := logic.NewAliPayOrderLogic()
				c.TradeNo = lst.TradeNo
				if _, err := c.AliPayTradeRefund(int64(balanceInfo.Amount), lst.TradeNo, "结束订单"); err != nil {
					logs.Error("AliPayTradeRefund", err)
					continue
				}

				// 余额修改
				tx, key := dbs.GormBegin("order refund")
				// 订单退款，退款至余额
				rechargeMoneyUpdateData := memberdao.NewMemberDao().UpdateBalanceAmount(tx, &membermodel.MemberPclBalance{
					MemberId:    memberInfo.ID,
					Amount:      -int(balanceInfo.Amount),
					Type:        4,
					TradeNo:     "R" + lst.TradeNo,
					Description: fmt.Sprintf(`退款提现`),
					CreateTime:  time.Now().Format("2006-01-02 15:04:05"),
					UpdateTime:  time.Now().Format("2006-01-02 15:04:05"),
				})
				if rechargeMoneyUpdateData.Err != nil {
					dbs.GormRollback(tx, key, rechargeMoneyUpdateData.Err)
					continue
				}
				dbs.GormCommit(tx, key)
				amount = amount - int64(balanceInfo.Amount)
			} else {
				continue
			}
		}
		if amount <= 0 {
			break
		}
	}
	// 300天后还有余额的-走转帐
	//if amount <= 0 {
	//	Response(ctx)("提现成功", CodeSuccess, false)(Error)
	//	return
	//}
	//memberInfo := memberdao.NewMemberDao().GetMemberInfoByOpenidAndAppId(param.Openid, param.Appid).Unwrap().(*membermodel.MembersModel)
	//if memberInfo.Balance != amount {
	//	Response(ctx)("提现失败", CodeError, false)(Error)
	//	return
	//}
	//// 会员ID与当前登录ID不一致
	//if userId != memberInfo.ID {
	//	Response(ctx)("提现失败", CodeError, false)(Error)
	//	return
	//}
	//
	//wc := logic.NewSettingLogic().GetPaySettingByAppid(param.Appid)
	//
	//// 发起提现
	//err = logic.NewOrderLogic().HandleRefundTransfersByXcx(param.Amount, param.Openid, param.Appid, memberInfo, wc, ctx.ClientIP())
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeSuccess, false)(OK)
	//	return
	//}



	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleMemberPhone 更新用户信息
func HandleMemberPhone(ctx *gin.Context) {
	param := &request.MemberInfoReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	log.Println("打印测试数据-更新用户信息", param)

	var phoneInfo = map[string]interface{}{}
	if param.EncryptedData == "" && param.Iv == "" {
		Response(ctx)("获取会员授权信息成功", CodeSuccess, phoneInfo)(OK)
		return
	}

	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	openid, err := helper.GetUserNameFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 获取sessionKey
	rdbSessionKey := utils.Join(openid, "-sessionKey")
	sessionKey := global.Rdb.Get(ctx, rdbSessionKey).Val()

	log.Println("打印测试session", openid, rdbSessionKey, sessionKey)

	// 解密微信数据
	str, err := wechatpay.Dncrypt(param.EncryptedData, sessionKey, param.Iv)

	if err != nil {
		Response(ctx)("解密失败", CodeError, err.Error())(Error)
		return
	}
	log.Println("解密后的用户信息", str)

	_ = json.Unmarshal([]byte(str), &phoneInfo)

	// 更新用户信息逻辑
	logic.NewWxAuthLogic().UpdateMemberPhone(phoneInfo["phoneNumber"].(string), userId)

	Response(ctx)("获取会员授权信息成功", CodeSuccess, phoneInfo)(OK)
}

// HandleUnifiedOrder 统一下单-押金支付并生成支付签名V2版本
func HandleUnifiedOrder(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	log.Println("打印统一下订单，请求参数处理", userId, err)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	// 请求参数处理
	param := &request.CreateOrderReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.ClientIp = ctx.ClientIP()
	param.UserId = userId

	log.Println("打印统一下订单，请求参数处理", param)

	if param.Openid == "" || param.DeviceSn == "" {
		Response(ctx)("参数错误,请重新扫码", CodeError, nil)(OK)
		return
	}

	// 验证是否是黑名单 - 废弃由登录的用户状态来判断
	//if b := helper.CheckOpenidStatus(param.Openid); b { // 100006
	//	Response(ctx)("CodeInvalidOpenid", CodeInvalidOpenid, nil)(OK)
	//	return
	//}

	// 判断是否有订单
	orderInfo := dao.NewOrderDao().GetOrderInfoByOpenidAndSn(param.Openid, param.DeviceSn).Unwrap().(*orders.OrderModel)
	if orderInfo.State == 2 { // 100007
		Response(ctx)("CodeOrderExits", CodeOrderExits, orderInfo)(OK)
		return
	}

	// 下订单业务逻辑
	orderLogic := logic.NewOrderLogic()
	respData, err := orderLogic.HandleWxUnifiedOrder(param)
	if err != nil {
		Response(ctx)(err.Error(), CodeError, respData)(Error)
		return
	}

	// 使用指定优惠券
	if dao.NewCouponDao().SetUnderCouponInfo(&couponinfo.CouponInfo{TradeNo: orderLogic.TradeNo, Id: param.CouponInfoId, Status: 1}).Err != nil {
		Response(ctx)(err.Error(), CodeError, respData)(Error)
		return
	}

	resultData := orderLogic.HandleMakeSign(respData) // 二次签名
	Response(ctx)("", CodeSuccess, resultData.ToJson())(OK)
}

func HandleOrderCreate(ctx *gin.Context)  {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &struct {
		TradeNo   string    `json:"tradeNo" form:"tradeNo"`
		AppId     string    `json:"appId" form:"appId"`
		Openid    string    `json:"openid" form:"openid"`
	}{}

	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	wc := logic.NewSettingLogic().GetPaySettingByAppid(param.AppId)
	resultData, _ := wechatpay.ApiQueryTransactionsOrder(param.TradeNo, wc)

	// 创建订单
	_ = logic.NewNotifyLogic().DepositPayResultNotifyV3(resultData, userId)

	orderInfo := dao.NewOrderDao().GetOrderInfoByTradeNo(param.TradeNo).Unwrap().(*orders.OrderModel)
	Response(ctx)("CodeOrderExits", CodeSuccess, orderInfo)(OK)
}

// JSAPI 下单V3
func HandleTransactionsPayV3(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// todo 参数校验
	param := &request.CreateOrderReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.ClientIp = ctx.ClientIP()
	param.UserId = userId
	if param.Openid == "" || param.DeviceSn == "" {
		Response(ctx)("参数错误,请重新扫码", CodeError, false)(OK)
		return
	}
	if param.Appid == "" {
		Response(ctx)("appid参数错误", CodeError, false)(OK)
		return
	}
	orderInfo := dao.NewOrderDao().GetOrderInfoByOpenidAndSn(param.Openid, param.DeviceSn).Unwrap().(*orders.OrderModel)
	if orderInfo.State == 2 {
		Response(ctx)("CodeOrderExits", CodeOrderExits, orderInfo)(OK) // 已有订单
		return
	}

	wc := logic.NewSettingLogic().GetPaySettingByAppid(param.Appid)

	respData, tradeNo, err := logic.NewOrderLogic().HandleWxTransactionsPayV3(param, wc)
	if err != nil {
		Response(ctx)(err.Error(), CodeError, respData)(Error)
		return
	}
	logs.Info("打印测试========", respData.ToJson())


	// 使用指定优惠券
	if dao.NewCouponDao().SetUnderCouponInfo(&couponinfo.CouponInfo{TradeNo: respData.Get("out_trade_no"), Id: param.CouponInfoId, Status: 1}).Err != nil {
		Response(ctx)(err.Error(), CodeError, respData)(Error)
		return
	}

	// 调起支付
	resultData := logic.NewOrderLogic().HandleMakeSignV3(respData, wc, tradeNo) // 二次签名
	logs.Info("调起微信支付签名", resultData.ToJson())
	Response(ctx)("", CodeSuccess, resultData.ToJson())(OK)
}

// HandleEndOrder 结束订单
func HandleEndOrder(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &request.CloseOrderReq{}
	log.Println("结束订单信息：")
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.EndTime = time.Now().Unix()
	log.Println("结束订单信息：", param)
	//settResp := logic.NewOrderLogic().HandleWxEndOrder(param)
	settResp := logic.NewOrderLogic().HandleWxEndOrderV3(param, userId)

	Response(ctx)("", CodeSuccess, settResp)(OK)
}

// HandleEndOrder 结束订单本地测试
func HandleCloseOrderTest(ctx *gin.Context) {
	param := &request.CloseOrderReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.EndTime = time.Now().Unix()

	settResp := logic.NewOrderLogic().HandleWxEndOrder(param)

	Response(ctx)("", CodeSuccess, settResp)(OK)
}

// 开始计费时长更新
func HandleUpdateAwardTimeOrder(ctx *gin.Context) {
	param := &request.WxUpdateAwardTime{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	log.Println("开始计费时长更新：", param)

	if err := logic.NewOrderLogic().HandleUpdateAwardTimeOrder(param); err != nil {
		Response(ctx)(err.Error(), CodeError, false)(Error)
		return
	}
	Response(ctx)("", CodeSuccess, true)(OK)
}

// 获取token
func HandleGetTokenByOpenid(ctx *gin.Context) {
	param := &struct {
		Openid string `form:"openid" json:"openid" binding:"required"`
		Unionid string `form:"unionid" json:"appid"`
		Appid string `form:"appid" json:"appid"`
	}{}
	if param.Appid == "" { param.Appid = "wx69ad53d0d977209a" }
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	loginResult, err := logic.NewWxAuthLogic().HandleGetTokenLogic(param.Openid, param.Appid, param.Unionid)
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}

	loginResult.Host = global.Cfg.Ali.AliossPath
	Response(ctx)("", CodeSuccess, loginResult)(OK)
}
